package com.yilin.tms.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yilin.commons.util.MapUtil;
import com.yilin.commons.util.StringUtil;
import com.yilin.tms.core.application.PageData;
import com.yilin.tms.core.application.ReturnData;
import com.yilin.tms.core.commons.annotation.*;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.commons.utils.UserUtil;
import com.yilin.tms.core.commons.base.BaseController;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.entity.user.RoleType;
import com.yilin.tms.core.entity.user.UserType;
import com.yilin.tms.core.entity.user.organize.Cooperate;
import com.yilin.tms.core.entity.user.organize.Department;
import com.yilin.tms.core.entity.user.organize.Organize;
import com.yilin.tms.core.remote.IOrderRemote;
import com.yilin.tms.user.service.*;
import org.python.antlr.op.Or;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 组织管理
 */
@RestController
@RequestMapping("/user/organize/")
public class OrganizeController extends BaseController {

    @Resource
    private IAccountService accountService;
    @Resource
    private IOrganizeService organizeService;
    @Resource
    private IDepartmentService departmentService;
    @Resource
    private IHatchService hatchService;
    @Resource
    private IStatisticsService statisticsService;
    @Resource
    private IOrderRemote orderRemote;

    /**
     * 根据组织ID获取所有下级组织
     */
    @PostMapping("getBelowOrganizePage")
    public ReturnData<PageData<Organize>> getBelowOrganizePage(Organize query, Integer page, Integer limit) {
        if (StringUtil.isEmpty(query.getId())) query.setId(getLoginUser().getOrganizeId());
        if (StringUtil.isEmpty(query.getSort())) query.setSort("userType-ASC");
        PageData<Organize> childOrganizePage = organizeService.getBelowOrganizePage(query, page, limit);
        return jsonView(true, "获取成功", childOrganizePage);
    }

    /**
     * 获取所有授权组织
     */
    @PostMapping("getAuthorizedOrganizePage")
    @UserTarget({UserType.adminUser, UserType.platformUser})
    public ReturnData<PageData<Organize>> getAuthorizedOrganizePage(Organize query, Integer page, Integer limit) {
        ;
        PageData<Organize> childOrganizePage = organizeService.getAuthorizedOrganizePage(query, page, limit);
        return jsonView(true, "获取成功", childOrganizePage);
    }

    /**
     * 获取所有授权组织
     */
    @PostMapping("updateAuthorizedOrganize")
    @UserTarget({UserType.adminUser, UserType.platformUser})
    public ReturnData<PageData<Organize>> updateAuthorizedOrganize(String organizeId, Double number, Account.UserState userState) {
        ParamUtil.isNull(organizeId, "组织ID为空");
        ParamUtil.isNull(number, "组织ID为空");
        ParamUtil.isNull(userState, "组织ID为空");
        Organize organize = organizeService.getOrganizeById(organizeId);
        ParamUtil.isNull(organize, "获取组织信息失败");
        organize.setTruckNumber(number);
        organize.setAuthorizedState(userState);
        organizeService.updateById(organize);
        return jsonView(true, "保存成功");
    }

    /**
     * 孵化平台获取网货平台
     * 网络货运专用接口
     */
    @PostMapping("getPlatOrganizePage")
    public ReturnData<PageData<Organize>> getPlatOrganizePage(Organize query, Integer page, Integer limit) {
        if (StringUtil.isEmpty(query.getId())) query.setId(getLoginUser().getOrganizeId());
        if (StringUtil.isEmpty(query.getSort())) query.setSort("userType-ASC");
        PageData<Organize> childOrganizePage = organizeService.getLowerOrganizePage(query, page, limit);
        return jsonView(true, "获取成功", childOrganizePage);
    }

    /**
     * 根据组织ID获取直属下级组织
     */
    @PostMapping("getChildOrganizePage")
    public ReturnData<PageData<Organize>> getChildOrganizePage(Organize query, Integer page, Integer limit) {
        if (StringUtil.isEmpty(query.getId())) query.setId(getLoginUser().getOrganizeId());
        PageData<Organize> childOrganizePage = organizeService.getLowerOrganizePage(query, page, limit);
        return jsonView(true, "获取成功", childOrganizePage);
    }

    /**
     * 根据组织ID获取组织信息
     */
    @PostMapping("getOrganizeById")
    @NoLoginSecurity
    public ReturnData<Organize> getOrganizeById(String organizeId) {
        if (StringUtil.isEmpty(organizeId)) return jsonView(false, "组织ID不能为空！");
        Organize organize = organizeService.getOrganizeById(organizeId);
        return jsonView(true, "获取成功", organize);
    }

    /**
     * 批量ID查询
     */
    @PostMapping("getOrganizeListByIds")
    public ReturnData<List<Organize>> getOrganizeListByIds(String[] organizeIds) {
        List<Organize> organizeByQuery = organizeService.getOrganizeListByIds(organizeIds);
        return jsonView(true, "获取成功", organizeByQuery);
    }

    /**
     * 根据组织ID获取员工
     */
    @PostMapping("getEmployeeByOrganizeId")
    public ReturnData<List<Account>> getEmployeeByOrganizeId(String organizeId) {
        if (organizeId == null) organizeId = getLoginUser().getOrganizeId();
        List<Account> employeeByOrganizeId = accountService.getEmployeeByOrganizeId(organizeId);
        return jsonView(true, "获取成功", employeeByOrganizeId);
    }


    /**
     * 获取组织详细资料
     */
    @PostMapping("getUserOrganizeDetails")
    public ReturnData<Organize> getUserOrganizeDetails(String userId, String organizeId) {
        Organize organize;
        if (StringUtil.isNotEmpty(organizeId)) {
            organize = organizeService.getOrganizeById(organizeId);
        } else if (StringUtil.isNotEmpty(userId)) {
            Account user = accountService.getAccountById(userId);
            organize = organizeService.getOrganizeById(user.getOrganizeId());
        } else {
            organize = organizeService.getOrganizeById(getLoginUser().getOrganizeId());
        }
        //组织员工列表
        organize.setEmployeeList(accountService.getEmployeeByOrganizeId(organize.getId()));
        //组织合作关系
        if (!getLoginUser().getOrganizeId().equals(organize.getId())) {
            Cooperate cooperate = organizeService.getCooperate(getLoginUser(), organizeId);
            if (cooperate == null) {
                organize.setCooperateState(Cooperate.CooperateState.none);
            } else {
                organize.setCooperateState(cooperate.getCooperateState());
            }

        }
        //获取交易趋势
        ReturnData<List<Map<String, Object>>> tradingTrendDataList = orderRemote.getTradingTrendData(organizeId);
        List<Map<String, Object>> tradingTrendData = new ArrayList<>();
        for (Map<String, Object> tradingTrend : tradingTrendDataList.getData()) {
            tradingTrendData.add(MapUtil.generate(map -> map.put((String) tradingTrend.get("day"), tradingTrend.get("count"))));
        }
        organize.setTradingTrendData(tradingTrendData);
        //统计组织下所有账户（员工） 好评/中评/差评  投诉/仲裁/违规  [模拟]
        Map<String, Object> creditAssetsData = statisticsService.getCreditAssetsData(userId, organizeId);
        organize.setCreditAssetsData(creditAssetsData);
        return jsonView(SUCCESS_CODE, true, "获取成功", organize);
    }

    /**
     * 修改组织和管理账户信息
     *
     * @param account  account里面的organize 优先级比外层organize优先级高
     * @param organize 同时传入时优先account里的organize
     */
    @PostMapping("updateUserInfo")
    public ReturnData<Object> updateUserInfo(Account account, Organize organize) {
        if (organize != null && organize.getId() == null) organize.setId(getLoginUser().getOrganizeId());
        if (account.getId() == null) account.setId(getLoginUser().getId());
        if (account.getOrganize() != null) organize = account.getOrganize();
        Account localAccount = accountService.getAccountById(account.getId());
        if (localAccount == null) return jsonView(false, "未查询到该用户");
        Organize localOrganize = organizeService.getOrganizeById(localAccount.getOrganizeId());
        if (localOrganize == null) return jsonView(false, "未查询到该组织");
        if (getLoginUser().getRoleType() == RoleType.employee) {
            return jsonView(false, "您没有权限修改信息！");
        }
        if (getLoginUser().getUserType().ordinal() > localOrganize.getUserType().ordinal()) {
            return jsonView(false, "您没有权限修改信息！");
        }
        if (getLoginUser().getUserType() == localOrganize.getUserType() && !getLoginUser().getId().equals(localAccount.getId())) {
            return jsonView(false, "只能修改您自己的信息");
        }
        accountService.updateAccount(getLoginUser(), account, localAccount);
        if (organize != null) organizeService.updateOrganize(getLoginUser(), organize, localOrganize);
        UserUtil.updateLoginUser(localAccount);
        return jsonView(true, "修改成功");
    }

    /**
     * 修改组织信息
     */
    @PostMapping("updateOrganize")
    public ReturnData<Object> updateOrganize(Organize organize) {
        if (organize.getId() == null) organize.setId(getLoginUser().getOrganizeId());
        Organize localOrganize = organizeService.getOrganizeById(organize.getId());
        if (localOrganize == null) return jsonView(false, "未查询到该组织");
        if (getLoginUser().getUserType().ordinal() > localOrganize.getUserType().ordinal()) {
            return jsonView(false, "您没有权限修改组织信息！");
        }
        if (getLoginUser().getUserType() == localOrganize.getUserType() && getLoginUser().getRoleType() != RoleType.manager) {
            return jsonView(false, "您没有权限修改组织信息");
        }
        organizeService.updateOrganize(getLoginUser(), organize, localOrganize);
        return jsonView(true, "修改成功");
    }

    /**
     * 解散组织
     */
    @PostMapping("dismissOrganize")
    @SafeVerify
    public ReturnData<Object> dismissOrganize() {
        if (getLoginUser().getRoleType() != RoleType.manager) {
            return jsonView(false, "仅管理员可操作此功能！");
        }
        Organize organize = organizeService.getOrganizeById(getLoginUser().getOrganizeId());
        Boolean exist = ParamUtil.isSuccess(orderRemote.checkExistRunOrderByOrganizeId(organize.getId()));
        if (exist) return jsonErrView("组织下有订单尚未完成，为了不影响后续的订单进行，请先完成订单！");
        Boolean exist2 = ParamUtil.isSuccess(orderRemote.checkExistRunGoodsByOrganizeId(organize.getId()));
        if (exist2) return jsonErrView("组织下存在可执行货源，请作废所有货源后再销户");
        //实体中含有逻辑删除字段，此数据不会被真实删除
        organizeService.dismissOrganize(getLoginUser(), organize);
        return jsonView(SUCCESS_CODE, "操作成功");
    }

    /**
     * 每日任务
     * 月度 综合信用评分
     */
    @PostMapping("taskMonthlyUpdateRating")
    @SkipLoginVerify
    @NoLoginSecurity
    public ReturnData<Object> taskMonthlyUpdateRating() {
        organizeService.monthlyUpdateRating();
        return jsonView(SUCCESS_CODE, "操作成功");
    }

    //-----------------------------------------------------合作区------------------------------------------------------------------------

    /**
     * 获取合作货主ID列表
     * 用途：车主获取合作用户的货源
     */
    @PostMapping("getCooperateShipperIdList")
    @NotNull({"organizeId"})
    public ReturnData<List<String>> getCooperateShipperIdList(String organizeId) {
        List<String> cooperateShipperIdList = organizeService.getCooperateShipperIdList(organizeId);
        return jsonView(SUCCESS_CODE, "获取成功", cooperateShipperIdList);
    }

    /**
     * 获取同平台可合作所有车主列表
     */
    @PostMapping("getPlatCanCooperateOrganizePage")
    @NotNull({"page", "limit"})
    public ReturnData<PageData<Organize>> getPlatCanCooperateOrganizePage(Organize query, @Explain("页码") Integer page, @Explain("条数") Integer limit) {
        PageData<Organize> pageData = organizeService.getPlatCanCooperateOrganizePage(getLoginUser(), query, page, limit);
        return jsonView(SUCCESS_CODE, "获取成功", pageData);
    }

    /**
     * 获取合作申请列表
     */
    @PostMapping("getUserCooperateApplyList")
    public ReturnData<List<Cooperate>> getUserCooperateApplyList() {
        List<Cooperate> userCooperateApplyList = organizeService.getUserCooperateApplyList(getLoginUser());
        return jsonView(SUCCESS_CODE, "获取成功", userCooperateApplyList);
    }

    /**
     * 合作申请
     */
    @RequestMapping("applyUserCooperate")
    @NotNull({"targetOrganizeId"})
    public ReturnData<Object> applyUserCooperate(@Explain("组织ID") String targetOrganizeId) {
        organizeService.applyUserCooperate(getLoginUser(), targetOrganizeId);
        return jsonView(SUCCESS_CODE, "操作成功");
    }

    /**
     * 同意合作申请
     */
    @RequestMapping("agreeCooperateApply")
    @NotNull({"cooperateId"})
    public ReturnData<Object> agreeCooperateApply(@Explain("合作关系ID") String cooperateId) {
        organizeService.agreeCooperateApply(getLoginUser(), cooperateId);
        return jsonView(SUCCESS_CODE, "操作成功");
    }

    /**
     * 取消或拒绝合作
     */
    @RequestMapping("refuseCooperate")
    @NotNull({"targetOrganizeId"})
    public ReturnData<Object> refuseCooperate(@Explain("组织ID") String targetOrganizeId) {
        organizeService.refuseCooperate(getLoginUser(), targetOrganizeId);
        return jsonView(SUCCESS_CODE, "操作成功");
    }

    /**
     * 获取合作列表
     */
    @PostMapping("getCooperateOrganizePage")
    @NotNull({"page", "limit"})
    public ReturnData<PageData<Organize>> getCooperateOrganizePage(Organize query, @Explain("页码") Integer page, @Explain("条数") Integer limit) {
        PageData<Organize> pageData = organizeService.getCooperateOrganizePage(getLoginUser(), query, page, limit);
        return jsonView(SUCCESS_CODE, "获取成功", pageData);
    }

    /**
     * 获取合作关系
     */
    @RequestMapping("getCooperate")
    @NotNull({"targetOrganizeId"})
    public ReturnData<Cooperate> getCooperate(@Explain("组织ID") String targetOrganizeId) {
        Cooperate cooperate = organizeService.getCooperate(getLoginUser(), targetOrganizeId);
        return jsonView(SUCCESS_CODE, "操作成功", cooperate);
    }


    /**
     * 根据组织ID获取所有下级组织
     */
    @PostMapping("getBelowOrganizeBankCardPage")
    public ReturnData<PageData<Organize>> getBelowOrganizeBankCardPage(Organize query, Integer page, Integer limit) {
        if (StringUtil.isEmpty(query.getId())) query.setId(getLoginUser().getOrganizeId());
        if (StringUtil.isEmpty(query.getSort())) query.setSort("userType-ASC");
        PageData<Organize> childOrganizePage = organizeService.getBelowOrganizeBankCardPage(query, page, limit);
        return jsonView(true, "获取成功", childOrganizePage);
    }


//
//    /**
//     * 货主公司申请加入集团
//     *
//     * @param groupOrganizeId 加入的集团ID
//     */
//    @PostMapping("shippergroupCompanyApply")
//    @ResponseBody
//    public ReturnData<Object> shippergroupCompanyApply(String groupOrganizeId) {
//        if (loginUser.getUserType() != UserType.shipperUser) {
//            return jsonView(false, "仅限货主用户访问");
//        }
//        if (StringUtil.isEmpty(groupOrganizeId)) {
//            return jsonView(false, "集团ID为空");
//        }
//        if (loginUser.getRoleType() != RoleType.manager) {
//            return jsonView(false, "您不是管理员");
//        }
//        if (loginUser.getOrganType() == OrganType.group) {
//            return jsonView(false, "您已是集团");
//        }
//        Organize myOrganize = organizeService.getOrganizeById(loginUser.getOrganizeId());
//        if (myOrganize.getGroupApply() == Organize.GroupApply.apply) {
//            return jsonView(false, "您已发出申请");
//        }
//        if (myOrganize.getGroupApply() == Organize.GroupApply.success) {
//            return jsonView(false, "您已加入集团");
//        }
//        Organize groupOrganize = organizeService.getOrganizeById(groupOrganizeId);
//        if (groupOrganize == null) {
//            return jsonView(false, "未查询到该集团");
//        }
//        if (groupOrganize.getOrganType() != OrganType.group) {
//            return jsonView(false, "该组织并不是集团");
//        }
//        if (groupOrganize.getUserType() != myOrganize.getUserType()) {
//            return jsonView(false, "所选择公司用户类型不一致");
//        }
//        organizeService.shippergroupCompanyApply(loginUser, myOrganize, groupOrganize);
//        return jsonView(true, "申请成功");
//    }

//    /**
//     * 货主集团子公司审核列表
//     */
//    @PostMapping("groupCompanyApplyList")
//    @ResponseBody
//    public ReturnData<Object> groupCompanyApplyList() {
//        if (loginUser.getUserType() != UserType.shipperUser) {
//            return jsonView(false, "仅限货主用户访问");
//        }
//        if (loginUser.getRoleType() != RoleType.manager) {
//            return jsonView(false, "您不是管理员");
//        }
//        if (loginUser.getOrganType() != OrganType.group) {
//            return jsonView(false, "您不是集团组织");
//        }
//        List<Organize> organizeList = organizeService.getGroupChildCompanyList(loginUser, null, Organize.GroupApply.apply);
//        return jsonView(true, "获取成功", organizeList);
//    }
//
//    /**
//     * 审核子公司
//     *
//     * @param organizeId 被审核公司ID
//     * @param groupApply 审核结果
//     */
//    @PostMapping("verifyGroupCompanyApply")
//    @ResponseBody
//    public ReturnData<Object> verifyGroupCompanyApply(String organizeId, Organize.GroupApply groupApply) {
//        if (loginUser.getUserType() != UserType.shipperUser) {
//            return jsonView(false, "仅限货主用户访问");
//        }
//        if (loginUser.getRoleType() != RoleType.manager) {
//            return jsonView(false, "您不是管理员");
//        }
//        if (loginUser.getOrganType() != OrganType.group) {
//            return jsonView(false, "您不是集团组织");
//        }
//        if (StringUtil.isEmpty(organizeId)) {
//            return jsonView(false, "被审核公司ID为空");
//        }
//        if (groupApply == null) {
//            return jsonView(false, "审核结果为空");
//        }
//        Organize toOrganize = organizeService.getOrganizeById(organizeId);
//        if (toOrganize == null) {
//            return jsonView(false, "未查询到审核公司");
//        }
//        if (!toOrganize.getSuperiorOrganId().equals(loginUser.getOrganId())) {
//            return jsonView(false, "该公司并未申请加入您的集团");
//        }
//        if (toOrganize.getGroupApply() != Organize.GroupApply.apply) {
//            return jsonView(false, "该公司未在待审核状态");
//        }
//        organizeService.verifyGroupCompanyApply(loginUser, toOrganize, groupApply);
//        return jsonView(true, "审核成功");
//    }

//    /**
//     * 货主子公司退出集团管理
//     */
//    @PostMapping("exitOutGroupCompany")
//    @ResponseBody
//    public ReturnData<Object> exitOutGroupCompany() {
//        if (loginUser.getUserType() != UserType.shipperUser) {
//            return jsonView(false, "仅限货主用户访问");
//        }
//        if (loginUser.getRoleType() != RoleType.manager) {
//            return jsonView(false, "您不是管理员");
//        }
//        if (loginUser.getOrganType() == OrganType.group) {
//            return jsonView(false, "您是集团不能退出");
//        }
//        Organize organize = organizeService.getOrganizeById(loginUser.getOrganId());
//        if (organize.getGroupApply() != Organize.GroupApply.success || StringUtil.isEmpty(organize.getSuperiorOrganId())) {
//            return jsonView(false, "未加入集团");
//        }
//        organize.setGroupApply(Organize.GroupApply.none);
//        organize.setSuperiorOrganApplyTime(null);
//        organize.setSuperiorOrganManagerUserId(null);
//        organize.setSuperiorOrganManagerUserName(null);
//        organize.setSuperiorOrganId(null);
//        organize.setSuperiorOrganName(null);
//        organizeService.saveOrUpdateOrganize(organize);
//        return jsonView(true, "退出成功");
//    }
//
//    /**
//     * 集团强制移除子公司
//     */
//    @PostMapping("deleteChildCompany")
//    @ResponseBody
//    public ReturnData<Object> deleteChildCompany(String companyId) {
//        if (loginUser.getUserType() != UserType.shipperUser) {
//            return jsonView(false, "仅限货主用户访问");
//        }
//        if (loginUser.getRoleType() != RoleType.manager) {
//            return jsonView(false, "您不是管理员");
//        }
//        if (loginUser.getOrganType() != OrganType.group) {
//            return jsonView(false, "您不是集团");
//        }
//        if (StringUtil.isEmpty(companyId)) {
//            return jsonView(false, "公司ID不能为空");
//        }
//        Organize organize = organizeService.getOrganizeById(companyId);
//        if (organize == null) {
//            return jsonView(false, "未查询到该公司");
//        }
//        if (organize.getGroupApply() != Organize.GroupApply.success || StringUtil.isEmpty(organize.getSuperiorOrganId())) {
//            return jsonView(false, "未加入集团");
//        }
//        if (!organize.getSuperiorOrganId().equals(loginUser.getOrganId())) {
//            return jsonView(false, "该公司未加入您的集团");
//        }
//        organize.setGroupApply(Organize.GroupApply.none);
//        organize.setSuperiorOrganApplyTime(null);
//        organize.setSuperiorOrganManagerUserId(null);
//        organize.setSuperiorOrganManagerUserName(null);
//        organize.setSuperiorOrganId(null);
//        organize.setSuperiorOrganName(null);
//        organizeService.saveOrUpdateOrganize(organize);
//        return jsonView(true, "剔除成功");
//    }


    /**
     * 查组织下部门
     */
    @PostMapping("getDepartmentList")
    public ReturnData<Object> getDepartmentList(String organizeId) {
        if (StringUtil.isEmpty(organizeId)) return jsonView(false, "组织ID为空");
        List<Department> departmentList = departmentService.getDepartmentList(organizeId);
        return jsonView(true, "获取成功", departmentList);
    }

    /**
     * 保存修改部门
     */
    @PostMapping("saveDepartment")
    public ReturnData<Object> saveDepartment(Department department) {
        if (department == null) return jsonView(false, "部门为空");
        if (StringUtil.isEmpty(department.getDepartmentName())) return jsonView(false, "部门名称为空");
        if (StringUtil.isEmpty(department.getDepartmentManager())) return jsonView(false, "部门管理员为空");
        Department department1 = departmentService.saveOrUpdateDepartment(department);
        return jsonView(true, "获取成功", department1);
    }


    /**
     * 解散部门
     */
    @PostMapping("deleteDepartment")
    @ResponseBody
    public ReturnData<Object> deleteDepartment(String departmentId) {
        if (getLoginUser() == null) return jsonView(false, "请登录后在执行此操作");
        Department one = departmentService.getOne(new QueryWrapper<Department>().eq("id", departmentId));
        if (one == null) return jsonView(false, "此部门不存在");
        if (!getLoginUser().getId().equals(getLoginUser().getOrganizeManagerUserId()))
            return jsonView(false, "您不是管理员");
        departmentService.deleteDepartment(one);
        return jsonView(true, "解散部门成功");
    }

    //获取所有车队组织
    @PostMapping("getTruckOrganizeList")
    @ResponseBody
    @SkipLoginVerify
    public ReturnData<Object> getTruckOrganizeList() {
        List<Organize> list = organizeService.getTruckOrganizeList();
        return jsonView(true, "解散部门成功", list);
    }

}
